#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
桌面助手配置文件
用于自定义文件分类规则和程序设置
"""

import json
import os

class Config:
    """配置管理器"""
    
    def __init__(self):
        self.config_file = os.path.join(os.path.dirname(__file__), "config.json")
        self.default_config = self._get_default_config()
        self.config = self._load_config()
    
    def _get_default_config(self):
        """获取默认配置"""
        return {
            "file_categories": {
                "文档": [".doc", ".docx", ".pdf", ".txt", ".rtf", ".xls", ".xlsx", 
                        ".ppt", ".pptx", ".odt", ".ods", ".odp", ".wps", ".et", ".dps"],
                "图片": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".ico", 
                        ".svg", ".webp", ".psd", ".ai", ".eps"],
                "视频": [".mp4", ".avi", ".mkv", ".mov", ".wmv", ".flv", ".webm", 
                        ".m4v", ".3gp", ".rmvb", ".rm", ".asf"],
                "音频": [".mp3", ".wav", ".flac", ".aac", ".ogg", ".wma", ".m4a", 
                        ".ape", ".ac3", ".dts"],
                "压缩包": [".zip", ".rar", ".7z", ".tar", ".gz", ".bz2", ".xz", 
                          ".cab", ".iso", ".dmg"],
                "程序": [".exe", ".msi", ".deb", ".rpm", ".pkg", ".dmg", ".app", 
                        ".apk", ".bat", ".sh", ".com"],
                "快捷方式": [".lnk", ".url", ".desktop"],
                "代码": [".py", ".js", ".html", ".css", ".cpp", ".c", ".java", 
                        ".php", ".rb", ".go", ".rs", ".swift", ".kt"],
                "字体": [".ttf", ".otf", ".woff", ".woff2", ".eot"]
            },
            "settings": {
                "auto_backup": True,
                "confirm_before_organize": True,
                "skip_system_files": True,
                "create_date_folders": False,
                "max_backup_count": 10,
                "widget_position": {"x": 50, "y": 50},
                "widget_auto_hide": False,
                "widget_transparency": 0.9,
                "organize_subfolders": False,
                "exclude_patterns": ["*.tmp", "*.temp", "desktop.ini", "thumbs.db"],
                "language": "zh_CN"
            },
            "ui_settings": {
                "theme": "default",
                "window_size": {"width": 800, "height": 600},
                "always_on_top": False,
                "minimize_to_tray": False,
                "show_file_count": True,
                "show_file_size": True,
                "animation_enabled": True
            },
            "advanced": {
                "log_level": "INFO",
                "max_file_size_mb": 1000,
                "ignore_hidden_files": True,
                "custom_storage_path": "",
                "auto_clean_temp": False,
                "startup_scan": True
            }
        }
    
    def _load_config(self):
        """加载配置文件"""
        if not os.path.exists(self.config_file):
            self._save_config(self.default_config)
            return self.default_config.copy()
        
        try:
            with open(self.config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
                # 合并默认配置，确保新增的配置项不会丢失
                merged_config = self._merge_configs(self.default_config, config)
                return merged_config
        except (json.JSONDecodeError, FileNotFoundError):
            return self.default_config.copy()
    
    def _merge_configs(self, default, user):
        """合并配置，确保所有默认键都存在"""
        result = default.copy()
        for key, value in user.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = self._merge_configs(result[key], value)
            else:
                result[key] = value
        return result
    
    def _save_config(self, config):
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存配置文件失败: {e}")
    
    def get(self, key, default=None):
        """获取配置项"""
        keys = key.split('.')
        value = self.config
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        return value
    
    def set(self, key, value):
        """设置配置项"""
        keys = key.split('.')
        config = self.config
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        config[keys[-1]] = value
        self._save_config(self.config)
    
    def get_file_categories(self):
        """获取文件分类规则"""
        return self.config.get("file_categories", {})
    
    def add_file_extension(self, category, extension):
        """添加文件扩展名到指定分类"""
        if category not in self.config["file_categories"]:
            self.config["file_categories"][category] = []
        
        if extension not in self.config["file_categories"][category]:
            self.config["file_categories"][category].append(extension)
            self._save_config(self.config)
    
    def remove_file_extension(self, category, extension):
        """从指定分类中移除文件扩展名"""
        if category in self.config["file_categories"]:
            if extension in self.config["file_categories"][category]:
                self.config["file_categories"][category].remove(extension)
                self._save_config(self.config)
    
    def add_category(self, category, extensions=None):
        """添加新的文件分类"""
        if extensions is None:
            extensions = []
        self.config["file_categories"][category] = extensions
        self._save_config(self.config)
    
    def remove_category(self, category):
        """移除文件分类"""
        if category in self.config["file_categories"]:
            del self.config["file_categories"][category]
            self._save_config(self.config)
    
    def reset_to_default(self):
        """重置为默认配置"""
        self.config = self.default_config.copy()
        self._save_config(self.config)
    
    def export_config(self, filepath):
        """导出配置文件"""
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
            return True
        except Exception:
            return False
    
    def import_config(self, filepath):
        """导入配置文件"""
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                imported_config = json.load(f)
                self.config = self._merge_configs(self.default_config, imported_config)
                self._save_config(self.config)
            return True
        except Exception:
            return False

# 全局配置实例
config = Config()

# 便捷函数
def get_file_categories():
    """获取文件分类规则"""
    return config.get_file_categories()

def get_setting(key, default=None):
    """获取设置项"""
    return config.get(f"settings.{key}", default)

def set_setting(key, value):
    """设置配置项"""
    config.set(f"settings.{key}", value)

def get_ui_setting(key, default=None):
    """获取UI设置项"""
    return config.get(f"ui_settings.{key}", default)

def set_ui_setting(key, value):
    """设置UI配置项"""
    config.set(f"ui_settings.{key}", value)

if __name__ == "__main__":
    # 测试配置功能
    print("测试配置功能...")
    
    # 获取文件分类
    categories = get_file_categories()
    print(f"文件分类数量: {len(categories)}")
    
    # 获取设置
    auto_backup = get_setting("auto_backup")
    print(f"自动备份: {auto_backup}")
    
    # 设置新值
    set_setting("test_setting", "test_value")
    test_value = get_setting("test_setting")
    print(f"测试设置: {test_value}")
    
    print("配置功能测试完成！") 